//
//  CZAccountTool.m
//  OCKSFWeibo
//
//  Created by 盛 发 况 on 16/4/21.
//  Copyright © 2016年 盛 发 况. All rights reserved.
//

#import "CZAccountTool.h"
#import "CZAccount.h"
#import <MJExtension.h>
#import "CZAccountParam.h"
#import "CZHttpTool.h"

#define CZAuthorizeBaseUrl @"https://api.weibo.com/oauth2/authorize"
#define CZClient_id    @"326070450"
#define CZRedirect_uri  @"http://www.baidu.com"
#define CZClient_secret @"02a164b4858debb25917dba079b806db"

#define CZAccountFileName [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"account.data"]

@implementation CZAccountTool
// 类方法一般用静态变量代替成员属性
static CZAccount *_account;

+ (void)saveAccount:(CZAccount *)account {

    [NSKeyedArchiver archiveRootObject:account toFile:CZAccountFileName];
}

+ (CZAccount *)account {
    if (_account == nil) {
        
        _account = [NSKeyedUnarchiver unarchiveObjectWithFile:CZAccountFileName];
        // 判断下账号是否过期，如果过期直接返回Nil
        if ([[NSDate date] compare:_account.expires_date] != NSOrderedAscending) { //过期
            return nil;
        }
    }
    return _account;
}

+ (void)accountWithCode:(NSString *)code success:(void (^)())success failure:(void (^)(NSError *))failure {

    CZAccountParam *param = [[CZAccountParam alloc] init];
    param.client_id = CZClient_id;
    param.client_secret = CZClient_secret;
    param.grant_type = @"authorization_code";
    param.code = code;
    param.redirect_uri = CZRedirect_uri;
    
    [CZHttpTool Post:@"https://api.weibo.com/oauth2/access_token" parameters:param.mj_keyValues success:^(id responseObject) {
        
        CZAccount *account = [CZAccount accountWithDict:responseObject];
        [CZAccountTool saveAccount:account];
        
        if (success) {
            success();
        }
        
    } failure:^(NSError *error) {
        
        if (failure) {
            failure(error);
        }
    }];
    
    
}


@end









